package cn.smartopen.aispace.service.merchant;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.smartopen.aispace.base.BaseService;
import cn.smartopen.aispace.config.Config;
import cn.smartopen.aispace.entity.AppidEntity;
import cn.smartopen.aispace.entity.ServiceUser;
import cn.smartopen.aispace.mapper.AppIdMapper;
import cn.smartopen.aispace.mapper.ServiceUserMapper;

@Service
public class APPIDService extends BaseService{

    @Autowired
    ServiceUserMapper serviceUserMapper;
    @Autowired
    AppIdMapper appIdMapper;

    public ServiceUser getServiceUserByPkId(Long pk){
        var user = serviceUserMapper.getServiceUserByPkId(pk);
        return user;
    }

    public ServiceUser getServiceUserByPublicKey(String publicKey){
        if(publicKey.startsWith("0x")){
            publicKey = publicKey.substring(2);
        }
        var user = serviceUserMapper.getServiceUserByPublicKey(publicKey);
        return user;
    }

    /**
     * 创建APPID
     * @param appId
     * @param domainName
     * @param serviceUserPkId
     * @return
     */
    public String createAppId(AppidEntity appidEntity,Long serviceUserPkId){
        // 创建之前先查询一下是否超过了现在创建的最大限度
        var hasAppIdNum = appIdMapper.getServiceUserAppIdNum(serviceUserPkId);
        if(hasAppIdNum > Config.MAX_APP_ID_REGIST_NUM){
            return "超过了最大注册数量" ;
        }

        appIdMapper.createAppidEntity(appidEntity);
        return "SUCCESS";
    }

    public String getServiceUserPkIdByPublicKey(String publicKey) {
        String pkId = null;
        if(publicKey.startsWith("0x")){
            publicKey = publicKey.substring(2);
        }
        // 查询该用户信息 有则返回PK无则创建
        pkId = serviceUserMapper.getServiceUserPkIdByPublicKey(publicKey);
        if(pkId==null){
            ServiceUser serviceUser = new ServiceUser(publicKey);
            serviceUserMapper.createServiceUser(serviceUser);
            pkId = serviceUser.getPkId().toString();
        }
        return pkId;

    }

    public ArrayList<AppidEntity> getAppIdListByPublicKey(String publicKey) {

        if(publicKey.startsWith("0x")){
            publicKey = publicKey.substring(2);
        }


        var list = appIdMapper.selectAppIdListByServiceUserPublicKey(publicKey);

        return list;
    }

    public void deleteAppIdByPkIdAndPublicKey(Long pkId, String publicKey) {

        if(publicKey.startsWith("0x")){
            publicKey = publicKey.substring(2);
        }

        appIdMapper.deleteAppIdByPkIdAndPublicKey(pkId,publicKey);
    }
    
    
}
